package com.linxianqin.log.aspect;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.linxianqin.log.domain.Enum.BusinessStatusEnum;
import com.linxianqin.log.annotation.SysLog;
import com.linxianqin.log.domain.dto.SysLogDto;
import com.linxianqin.log.manager.AsyncFactory;
import com.linxianqin.log.manager.AsyncManager;
import com.linxianqin.log.utils.http.IPUtil;
import com.linxianqin.log.utils.JSON;
import com.linxianqin.log.utils.http.ServletUtils;
import com.linxianqin.log.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

/**
 * 功能描述：操作日志记录处理
 * @author lxq
 * @version 1.00
 * @Date 2020/12/7
 */
@Slf4j
@Aspect
@Component
public class SysLogAspect {

    /** 排除敏感属性字段 */
    public static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" };
    // 配置织入点
    @Pointcut("@annotation(com.linxianqin.log.annotation.SysLog),")
    public void logPointCut(){}

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
    {
        handleLog(joinPoint, null, jsonResult);
    }
    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e)
    {
        handleLog(joinPoint, e, null);
    }
    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try
        {
            // 获得注解
            SysLog controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null)
            {
                return;
            }
            // *========数据库日志=========*//
            SysLogDto sysLogDto = new SysLogDto();
            //获取当前的用户
//            logDto.setUsername(SecurityUtil.getUsername());
            //设置时间
            sysLogDto.setExcuteTime(new Date());
            //保存状态
            sysLogDto.setStatus(BusinessStatusEnum.SUCCESS.ordinal());
            //获取请求地址
            HttpServletRequest request = ServletUtils.getRequest();
            sysLogDto.setOperIp(IPUtil.getIpAddr(request));
            // 返回参数
            sysLogDto.setJsonResult(StringUtils.substring(JSON.marshal(jsonResult), 0, 2000));
            if (e != null)
            {
                sysLogDto.setStatus(BusinessStatusEnum.FAIL.ordinal());
                sysLogDto.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            sysLogDto.setMethod(className + "." + methodName + "()");

            // 设置请求方式
            sysLogDto.setRequestMethod(ServletUtils.getRequest().getMethod());
            //处理设置注解上的参数
            getControllerMethodDescription(controllerLog, sysLogDto);
            //保存数据库,后面采用异步方式
            AsyncManager.me().execute(AsyncFactory.recordOper(sysLogDto));
        }
        catch (Exception exp)
        {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }
    /**
     * 是否存在注解，如果存在就获取
     */
    private SysLog getAnnotationLog(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null)
        {
            return method.getAnnotation(SysLog.class);
        }
        return null;
    }

    /**
     * 取注解中对方法的描述信息 用于Controller层注解
     * @param log 日志
     * @param sysLogDto 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(SysLog log, SysLogDto sysLogDto) throws Exception{
        //设置action动作
        sysLogDto.setBusinessType(log.businessType().ordinal());
        //设置模块标题
        sysLogDto.setModule(log.module());
        //设置摘要
        sysLogDto.setAbstracting(log.abstracting());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData())
        {
            //获取参数的信息，传入到数据库中。
            setRequestValue(sysLogDto);
        }
    }

    /**
     * 获取请求的参数，放到log中
     * @param sysLogDto 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(SysLogDto sysLogDto) throws Exception{
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        if (StringUtils.isNotEmpty(map))
        {
            PropertyPreFilters.MySimplePropertyPreFilter excludefilter = new PropertyPreFilters().addFilter();
            excludefilter.addExcludes(EXCLUDE_PROPERTIES);
            String params = JSONObject.toJSONString(map, excludefilter);
            sysLogDto.setOperParam(StringUtils.substring(params, 0, 2000));
        }
    }
}
